#include <bits/stdc++.h>
using namespace std;
using ll = long long;
using pii = pair<int, int>;
#define rep(i, a, b) for (int i = (a); i <= (b); i++)
#define per(i, a, b) for (int i = (a); i >= (b); i--)
#define endl '\n'
const int N = 2e5 + 5;
const int MOD = 1e9 + 9;

int n, m;
int a[N], vis[N];
int cnt;
ll fac[N], inv[N];

ll fastpow(ll b, ll p) {
  ll res = 1;
  while (p) {
    if (p & 1) res = res * b % MOD;
    b = b * b % MOD;
    p >>= 1;
  }
  return res;
}
void init(int MX) {
  fac[0] = 1;
  rep(i, 1, MX) fac[i] = fac[i - 1] * i % MOD;
  inv[MX] = fastpow(fac[MX], MOD - 2);
  per(i, MX - 1, 0) inv[i] = inv[i + 1] * (i + 1) % MOD;
}
void dfs(int i) {
  if (vis[i]) return;
  vis[i] = 1;
  cnt++;
  dfs(a[i]);
}
ll f(ll x) {
  if (x <= 2) return 1;
  return fastpow(x, x - 2);
}
void solve() {
  cin >> n;
  rep(i, 1, n) cin >> a[i];
  rep(i, 1, n) vis[i] = 0;
  vector<int> v;
  rep(i, 1, n) {
    if (!vis[i]) {
      cnt = 0;
      dfs(i);
      v.push_back(cnt);
    }
  }
  ll ans = fac[n - v.size()];
  for (int x : v) {
    ans = ans * f(x) % MOD;
    ans = ans * inv[x - 1] % MOD;
  }
  cout << ans << endl;
}
int main() {
  ios::sync_with_stdio(0), cin.tie(0), cout.tie(0);
  init(1e5);
  int t;
  cin >> t;
  while (t--) solve();
  return 0;
}